package game;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.image.*;
import java.applet.*;
import java.net.URL;
import java.util.*;

public class Game extends Applet implements Runnable
{

	private static final long serialVersionUID = 1L;
	public static final int screenWidth  = 800;
	public static final int screenHeigth = 600;
	public static Random random = new Random();
	public static int intPause = 1;
	float time;
	BufferedImage backbuffer;
	BufferedImage cursor;
	Graphics graphic;
	boolean escapePressed = false;
	Thread gameLoop;
	static Random rand = new Random();
	static Game instance;
	Cursor customCursor;
	
	long lastTime;
	
	public static double loopTime;
	
	int fps = 60;
	long a, b;
	
	Image image;
	float x, y;
	int w, h;
	private static Game game;
	
	public void init()
	{
		this.backbuffer = new BufferedImage(screenWidth, screenHeigth, BufferedImage.TYPE_INT_RGB);
		this.graphic = backbuffer.createGraphics();
		addKeyListener(Keyboard.getInstance());
		addMouseListener(Mouse.getInstance());
		addMouseMotionListener(Mouse.getInstance());
		setFocusable(true);
		//this.lastTime = System.nanoTime();
		SceneManager.setup();
		this.cursor = new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB);
		this.setCursor(this.getToolkit().createCustomCursor(cursor, new Point(0, 0), "blank cursor"));
		customCursor = new Cursor(1, new Point2D.Double(0, 0), new Point2D.Double(23, 23));
	}

	public void start()
	{
		this.gameLoop = new Thread(this);
		this.gameLoop.start();
	}

	public void stop()
	{
		this.gameLoop = null;
	}

	public void run()
	{
		Thread t = Thread.currentThread();

		while (t == this.gameLoop)
		{
			try 
			{
				Thread.sleep(15);
			}
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
			repaint();
		}	
	}
		
	public void update(Graphics g)
	{		
		paint(g);
	
		long currentTime = 0;
		//currentTime = System.nanoTime();
		this.lastTime = currentTime;
		// FPS
		a = System.nanoTime();
		
		fps++;
		if (a - b >= 1000000000)
		{
			loopTime = (double)((1.0)/fps);
			fps = 1;
			b = a;
		}	
			game = this;
			SceneManager.scene.update();
			customCursor.update();
		
		time += Game.loopTime;
	}

	public void paint(Graphics g)
	{
		SceneManager.scene.draw(graphic);	
		customCursor.draw(graphic);
		g.drawImage(backbuffer, 0, 0, this);
	}
	
	public static void AbrirURL()
	{
		try  
		 {  
			 URL url = new URL("http://www.wavegames.com.br");
			 AppletContext a = Game.game.getAppletContext();
			 a.showDocument(url, "_blank");
		 }  
		 catch(Exception ex)  
		 {  
		 }  
	}
}